'use strict'

import { app, protocol, BrowserWindow, ipcMain, session, Menu } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const isDevelopment = process.env.NODE_ENV !== 'production'

let win

app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')

protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])

function createWindow() {
  Menu.setApplicationMenu(null)

  win = new BrowserWindow({
    width: 1200,
    height: 700,
    webPreferences: {
      nodeIntegration: true,
      webSecurity: false,
      webviewTag: true
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    win.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    // if (!process.env.IS_TEST) win.webContents.openDevTools()
  } else {
    createProtocol('app')
    win.loadURL('app://./index.html')
  }

  win.on('closed', () => {
    win = null
  })
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

app.on('ready', async () => {
  createWindow()
})

if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit();
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

ipcMain.on('check-status', (event) => {
  let sessdata = ''

  session.defaultSession.cookies.get({})
    .then((cookies) => {
      for (let i = 0; i < cookies.length; i++) {
        if (cookies[i].name == 'SESSDATA' && cookies[i].domain == '.bilibili.com') {
          sessdata = cookies[i].value
          break
        }
      }

      event.returnValue = sessdata
    })
})

ipcMain.on('clear-status', (event) => {
  session.defaultSession.cookies.get({})
    .then((cookies) => {
      cookies.forEach((cookie) => {
        let url = ''
        url += cookie.secure ? 'https://' : 'http://'
        url += cookie.domain.charAt(0) === '.' ? 'www' : ''
        url += cookie.domain
        url += cookie.path
        session.defaultSession.cookies.remove(url, cookie.name)
      })

      event.returnValue = 'clear'
    })
})

ipcMain.on('set-sessdata', (event, arg) => {
  const cookie = {
    url: 'https://wiki.biligame.com',
    domain: '.biligame.com',
    expirationDate: ((new Date()).valueOf() + 15552000000) / 1000,
    httpOnly: true,
    name: 'SESSDATA',
    secure: false,
    path: '/',
    value: arg
  }
  
  session.defaultSession.cookies.set(cookie)
    .then(() => {
      event.returnValue = 'sucess'
    }, (error) => {
      console.error(error)
    })
})